package com.ocm.commerceinteraction.ui;


import android.app.ActivityManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.MainActivity;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.UserDetailInfo;
import com.ocm.commerceinteraction.model.UserInGroupModel;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.loading.Loading;
import com.ocm.commerceinteraction.util.view.MyAlertDialog;
import com.ocm.commerceinteraction.util.view.RoundImageView;
import com.ocm.commerceinteraction.util.view.SlideSwitch;
import com.ocm.commerceinteraction.util.view.percentsupport.PercentRelativeLayout;
import com.squareup.picasso.Picasso;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

/**
 * A simple {@link Fragment} subclass.
 */
@EFragment(R.layout.fragment_user_detail)
public class UserDetailFragment extends BaseFragment {

    @ViewById(R.id.toptitle_title)
    TextView topTitle;
    @ViewById(R.id.name)
    TextView name;
    @ViewById(R.id.signature)
    TextView signature;
    @ViewById(R.id.head_img)
    ImageView headImg;
    @ViewById(R.id.assistant_pipe)
    PercentRelativeLayout assistantPipe;  //副管
    @ViewById(R.id.parttime_pipe)
    PercentRelativeLayout parttimePipe; //临管
    @ViewById(R.id.move_out)
    PercentRelativeLayout moveOut; //拉入黑名单
    @ViewById(R.id.no_speak)
    PercentRelativeLayout noSpeak;//禁言开关
    @ViewById(R.id.friend_btn)
    TextView friendBtn;//加好友
    @ViewById(R.id.ss_set_slave_manager_switch)
    SlideSwitch assistantPipeSwitch; //副管开关
    @ViewById(R.id.ss_set_temporary_manager_switch)
    SlideSwitch parttimePipeSwitch;//临管开关
    @ViewById(R.id.ss_blak_list_switch)
    SlideSwitch moveOutSwitch;//拉入黑名单
    @ViewById(R.id.ss_gag_switch)
    SlideSwitch noSpeakSwitch;//禁言开关
    @ViewById(R.id.tv_grade)
    TextView tv_grade;
    String userUniqId;
    String groupUniqId;
    int from;
    boolean block;//是否是点击开关后设置的，true 是 false 不是
    boolean parttimePipeBlock;//是否是设置临管之后设置的，true 是 false 不是
    boolean assistantPipeSwitchBlock;//是否是设置副管之后设置的，true 是 false 不是

    @Override
    @AfterViews
    void initView() {
        topTitle.setText("详细信息");
        userUniqId = getArguments().getString("userUniqId");
        from = getArguments().getInt("from");
        if (from == MethedUtil.FROM_FRIEND)
            hide();
        else {
            show();
            groupUniqId = getArguments().getString("groupUniqId");
        }
        block = false;
        parttimePipeBlock = true;
        assistantPipeSwitchBlock  = true;
        getLoginStatue();//根据登录者等级状态设置开关权限
        getGroupUserData();//设置被查看者的开关界面
        setSwitchListener();//设置开关的监听事件
        getUserInfo();//获取用户信息
    }

    //获取登陆者的状态
    void getLoginStatue() {
        requestUrl = RequestAddr.userDetailInfoInGroup + "?group_uniq_id=" + groupUniqId
                + "&user_uniq_id=" + GlobalApplication.loginModel.getData().getUser_uniq_id();
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Log.i("liuwenjie", "succes");
                setLevelSwtich(o); //设置开关的状态
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.i("liuwenjie", "fail");
            }
        });
    }

    void getGroupUserData() {
        requestUrl = RequestAddr.userDetailInfoInGroup + "?group_uniq_id=" + groupUniqId
                + "&user_uniq_id=" + userUniqId;
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Log.i("liuwenjie", "succes");
                setSwitchState(o); //设置开关的状态
                block = true;//初始状态设置完毕后，再打开监听点击事件
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.i("liuwenjie", "fail");
            }
        });
    }

    UserInGroupModel userInGroupModel;

    private void setSwitchState(Object object) {
        try {
            userInGroupModel = GlobalApplication.gson.fromJson(object.toString(), UserInGroupModel.class);
        } catch (JsonSyntaxException e) {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        switch (userInGroupModel.getData().getLevel()) {
            case 1:
                assistantPipeSwitch.setState(false);
                parttimePipeSwitch.setState(false);
                break;
            case 2:
                assistantPipeSwitch.setState(true);
                parttimePipeSwitch.setState(false);
                break;
            case 3:
                assistantPipeSwitch.setState(false);
                parttimePipeSwitch.setState(true);
                break;
            case 4:
                assistantPipeSwitch.setState(false);
                parttimePipeSwitch.setState(false);
                break;
        }

        if (userInGroupModel.getData().getIs_black() == 1) {
            moveOutSwitch.setState(true);
        } else
            moveOutSwitch.setState(false);

        if (userInGroupModel.getData().getAble_send_msg() == 1) {
            noSpeakSwitch.setState(false);
        } else
            noSpeakSwitch.setState(true);

    }

    void setSwitchListener() {
        //副管按钮的开与关
        assistantPipeSwitch.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open(int viewId) {
               if (block){
                   requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                           + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_level" + "&param_value=" +
                           2;
                   GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                       @Override
                       public void onSuccess(Object o) {
                           super.onSuccess(o);
                           Log.i("liuwenjie", "open succes");
                           parttimePipeBlock = false;
                           parttimePipeSwitch.setState(false);
                       }

                       @Override
                       public void onFailure(Throwable t, int errorNo, String strMsg) {
                           super.onFailure(t, errorNo, strMsg);
                           Log.i("liuwenjie", "fail");
                       }
                   });
               }

            }

            @Override
            public void close(int viewId) {
                if (block&&assistantPipeSwitchBlock){
                    requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                            + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_level" + "&param_value=" +
                            4;
                    GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                        @Override
                        public void onSuccess(Object o) {
                            super.onSuccess(o);
                            Log.i("liuwenjie", "close succes");
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                            Log.i("liuwenjie", "fail");
                        }
                    }
                    );
                }
                assistantPipeSwitchBlock = true;

            }
        });
        //临管按钮的开与关
        parttimePipeSwitch.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open(int viewId) {
                if (block) {
                    requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                            + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_level" + "&param_value=" +
                            3;
                    GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                        @Override
                        public void onSuccess(Object o) {
                            super.onSuccess(o);
                            Log.i("liuwenjie","open succes");
                            assistantPipeSwitchBlock = false;
                            assistantPipeSwitch.setState(false);

                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                            Log.i("liuwenjie", "open fail");
                        }
                    });
                }
            }

            @Override
            public void close(int viewId) {
                if (block&&parttimePipeBlock){
                requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                        + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_level" + "&param_value=" +
                        4;
                GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);
                        Log.i("liuwenjie", "close succes");

                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        Log.i("liuwenjie", "fail");
                    }
                });

                }
                parttimePipeBlock = true;


            }
        });
        //拉入黑名单的开与关
        moveOutSwitch.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open(int viewId) {
                if (block){
                requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                        + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_isblack" + "&param_value=" +
                        1;
                GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);
                        Log.i("liuwenjie", "succes");

                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        Log.i("liuwenjie", "fail");
                    }
                });
                }

            }

            @Override
            public void close(int viewId) {
                if (block){
                requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                        + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_isblack" + "&param_value=" +
                        2;
                GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);
                        Log.i("liuwenjie", "succes");

                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        Log.i("liuwenjie", "fail");
                    }
                });
                }
            }
        });
        //禁言按钮的开与关
        noSpeakSwitch.setSlideListener(new SlideSwitch.SlideListener() {
            @Override
            public void open(int viewId) {
                if (block) {
                    requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                            + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_able_send_msg" + "&param_value=" +
                            2;
                    GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                        @Override
                        public void onSuccess(Object o) {
                            super.onSuccess(o);
                            Log.i("liuwenjie", "succes");

                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                            Log.i("liuwenjie", "fail");
                        }
                    });
                }
            }

            @Override
            public void close(int viewId) {
                if (block){
                requestUrl = RequestAddr.editGroupInfo + "?group_uniq_id=" + groupUniqId
                        + "&user_uniq_id=" + userUniqId + "&param_name=" + "edit_able_send_msg" + "&param_value=" +
                       1;
                GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);
                        Log.i("liuwenjie", "succes");

                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        Log.i("liuwenjie", "fail");
                    }
                });
                }
            }
        });
    }

    //设置管理员，副管，临管等不同人的开关权限
    UserInGroupModel mySelfLevle;

    void setLevelSwtich(Object object) {
        try {
            mySelfLevle = GlobalApplication.gson.fromJson(object.toString(), UserInGroupModel.class);
        } catch (JsonSyntaxException e) {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        switch (mySelfLevle.getData().getLevel()) {
            case 1:
                assistantPipe.setVisibility(View.VISIBLE);
                parttimePipe.setVisibility(View.VISIBLE);
                noSpeak.setVisibility(View.VISIBLE);
                friendBtn.setVisibility(View.VISIBLE);
                moveOut.setVisibility(View.VISIBLE);
                break;
            case 2:
                assistantPipe.setVisibility(View.VISIBLE);
                parttimePipe.setVisibility(View.VISIBLE);
                noSpeak.setVisibility(View.VISIBLE);
                friendBtn.setVisibility(View  .VISIBLE);
                moveOut.setVisibility(View.VISIBLE);
                break;
            case 3:
                assistantPipe.setVisibility(View.GONE);
                parttimePipe.setVisibility(View.GONE);
                noSpeak.setVisibility(View.VISIBLE);
                friendBtn.setVisibility(View.VISIBLE);
                moveOut.setVisibility(View.GONE);
                break;
            case 4:
                assistantPipe.setVisibility(View.GONE);
                parttimePipe.setVisibility(View.GONE);
                noSpeak.setVisibility(View.GONE);
                friendBtn.setVisibility(View.VISIBLE);
                moveOut.setVisibility(View.GONE);
                break;
        }

    }

    void hide() {
        assistantPipe.setVisibility(View.GONE);
        parttimePipe.setVisibility(View.GONE);
        noSpeak.setVisibility(View.GONE);
        friendBtn.setVisibility(View.GONE);
        moveOut.setVisibility(View.GONE);
    }

    void show() {
        assistantPipe.setVisibility(View.VISIBLE);
        parttimePipe.setVisibility(View.VISIBLE);
        noSpeak.setVisibility(View.VISIBLE);
        friendBtn.setVisibility(View.VISIBLE);
        moveOut.setVisibility(View.VISIBLE);
    }

    @Override
    @Click({R.id.back_btn, R.id.friend_btn})
    void Click(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                //   ImageSelectorMainActivity.getFragmentMangerinstance().popBackStack();
                if (isAppOnForeground(MainActivity.class.getName())) {
                    MainActivity.getFragmentMangerinstance().popBackStack();
                } else if (isAppOnForeground(ChatActivity.class.getName())) {
                    ChatActivity.getFragmentMangerinstance().popBackStack();
                }
                break;
            case R.id.friend_btn:
                showEditDiallog("说点什么吧");
                break;
        }
    }

    //ControlActivity.class.getName()
    public boolean isAppOnForeground(String className) {
        ActivityManager manager = (ActivityManager) GlobalApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(className);
    }

    MyAlertDialog ad;

    void showEditDiallog(String title) {
        ad = new MyAlertDialog(getActivity());
        ad.setTitle(title);
        ad.setMessage("");
        ad.setNegativeButton("   确定    ", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
                addUser(ad.getMessage());
            }
        });

        ad.setPositiveButton("", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }

    void addUser(String msg) {

        String requestUrl = RequestAddr.addFriendRequest +
                "?friend_uniq_id=" + userUniqId + "&keywords=" + msg;
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Loading.stopLoading();
                Toast.makeText(getActivity(), "成功发送请求", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Loading.stopLoading();
                Toast.makeText(getActivity(), strMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 处理返回基本结构信息数据
     *
     * @param object  返回json结构
     */
    BaseModel baseModel;

    protected void dealBaseData(Object object) {
        try {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
        } catch (JsonSyntaxException e) {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
        }
        Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
    }

    void getUserInfo() {
        requestUrl = RequestAddr.userDetailInfo +
                "?user_uniq_id=" + userUniqId;

        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Loading.stopLoading();
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Loading.stopLoading();
            }
        });
    }

    UserDetailInfo userDetailInfo;

    void dealData(Object object) {
        try {
            userDetailInfo = gson.fromJson(object.toString(), UserDetailInfo.class);
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        name.setText(userDetailInfo.getData().getNick());
        tv_grade.setText(userDetailInfo.getData().getGrade());
        if (userDetailInfo.getData().getSignatrure() == null || userDetailInfo.getData().getSignatrure().equals(""))
            signature.setText("此人很懒，还没有留下一句话");
        else{
            signature.setText(userDetailInfo.getData().getSignatrure());
        }

        LogHelper.i("getIcon:"+RequestAddr.baseUrl + userDetailInfo.getData().getIcon());
//        Glide.with(MainActivity.getInstance()).load(RequestAddr.baseUrl + userDetailInfo.getData().getIcon()).placeholder(R.drawable.ease_default_avatar).into(headImg);
        Picasso.with(getActivity()).load(RequestAddr.baseUrl + userDetailInfo.getData().getIcon()).into(headImg);
    }
}
